package com.haibara.aiojquestionservice.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.haibara.aiojcommon.common.*;
import com.haibara.aiojcommon.constant.CommonConstant;
import com.haibara.aiojcommon.constant.UserConstant;
import com.haibara.aiojcommon.exception.BusinessException;
import com.haibara.aiojcommon.exception.ThrowUtils;
import com.haibara.aiojfeignclient.client.UserClient;
import com.haibara.aiojmodel.model.dto.question.*;
import com.haibara.aiojmodel.model.dto.questionsubmit.JudgeInfo;
import com.haibara.aiojmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.haibara.aiojmodel.model.dto.questionsubmit.QuestionSubmitQueryPageRequest;
import com.haibara.aiojmodel.model.entity.Question;
import com.haibara.aiojmodel.model.entity.QuestionSubmit;
import com.haibara.aiojmodel.model.entity.User;
import com.haibara.aiojmodel.model.enums.QuestionSubmitLanguageEnum;
import com.haibara.aiojmodel.model.enums.QuestionSubmitStatusEnum;
import com.haibara.aiojmodel.model.vo.JudgeVO;
import com.haibara.aiojmodel.model.vo.QuestionSubmitViewVO;
import com.haibara.aiojmodel.model.vo.QuestionVO;
import com.haibara.aiojquestionservice.service.QuestionService;
import com.haibara.aiojquestionservice.service.QuestionSubmitService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;



@RestController
@Slf4j
@Api(tags = "question")
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserClient userClient;

    @Resource
    private QuestionSubmitService questionSubmitService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1.从QuestionAddRequest中获取信息
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<String> tags = questionAddRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        if(judgeCase != null && !judgeCase.isEmpty()){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        // 2.设置题目默认信息
        questionService.validQuestion(question, true);
        User loginUser = userClient.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setExampleCode(questionAddRequest.getExampleCode());
        question.setAcceptedNum(0);
        question.setSubmitNum(0);
        boolean result = questionService.save(question);

        // 3.向代码沙箱发送JudgeCode
        QuestionCode questionCode = new QuestionCode();
        questionCode.setQuestionId(question.getId());
        questionCode.setCode(questionAddRequest.getJudgeCode());
        addJudgeCode(questionCode);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 向沙箱发送JudgeCode
     * @param questionCode
     */
    private void addJudgeCode(QuestionCode questionCode){
        String url = "http://localhost:8090/codesandbox/getCode";
        String json = JSONUtil.toJsonStr(questionCode);
        HttpUtil.createPost(url)
                .body(json)
                .execute();
    }

    /**
     * 删除
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userClient.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人且管理员可删除
        if(!userClient.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        if(!oldQuestion.getUserId().equals(user.getId())){
            throw new BusinessException(ErrorCode.ONLY_CREATOR_ERROR);
        }
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
        if(judgeCase != null && !judgeCase.isEmpty()){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);

        // 将修改后的JudgeCode发送给沙箱
        QuestionCode questionCode = new QuestionCode();
        questionCode.setQuestionId(question.getId());
        questionCode.setCode(question.getJudgeCode());
        addJudgeCode(questionCode);

        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取 题目VO信息
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 获取上一次提交的代码
     * @param id
     * @return
     */
    @GetMapping("/history")
    public String getHistoryCode(long id, HttpServletRequest request) {
        return questionSubmitService.getHistoryCode(id,request);
    }

    /**
     * 获取题目示例代码
     * @param id
     * @return
     */
    @GetMapping("/example")
    public String getExampleCode(long id) {
        return questionSubmitService.getExampleCode(id);
    }

    /**
     * 根据 id 获取 题目信息
     * @param id id
     * @return {@link BaseResponse}<{@link QuestionVO}>
     */
    @GetMapping("/get")
    public BaseResponse<Question> getQuestionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userClient.getLoginUser(request);
        if (!question.getUserId().equals(loginUser.getId()) && !userClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(question);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
            HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        questionQueryRequest.setSortField("id");
        questionQueryRequest.setSortOrder(CommonConstant.SORT_ORDER_ASC);
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 获取Question Page 并将其处理为 QuestionVO Page
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
            HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userClient.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionEditRequest.getJudgeCase();
        if(judgeCase != null && !judgeCase.isEmpty()){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionEditRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        User loginUser = userClient.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 修改示例代码和判题代码
        question.setExampleCode(questionEditRequest.getExampleCode());
        question.setJudgeCode(questionEditRequest.getJudgeCode());

        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取题目列表（仅管理员）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                   HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }


    // questionSubmit

    @GetMapping("/get/language")
    public BaseResponse<List<String>> getCodeLanguage() {
        return ResultUtils.success(QuestionSubmitLanguageEnum.getValues());
    }

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return resultNum 本次点赞变化数
     */
    @PostMapping("/question-submit/do")
    public BaseResponse<Integer> doSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
                                          HttpServletRequest request) {
        if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 登录才能点赞
        final User loginUser = userClient.getLoginUser(request);
        long result = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);
        return ResultUtils.success(Math.toIntExact(result));
    }

    /**
     * 分页获取题目提交列表
     * @param questionSubmitQueryRequest
     * @return
     */
    @GetMapping("/question-submit/list/page")
    public BaseResponse<Page<QuestionSubmitViewVO>> listQuestionSubmitByPage(QuestionSubmitQueryPageRequest questionSubmitQueryRequest) {
        long size = questionSubmitQueryRequest.getPageSize();
        long pageIndex = (questionSubmitQueryRequest.getCurrent() - 1) * size;
        String title = questionSubmitQueryRequest.getTitle();
        String language = questionSubmitQueryRequest.getLanguage();
        return ResultUtils.success(questionSubmitService.listQuestionSubmitByPage(title, language, pageIndex, size));
    }

    @GetMapping("/question-submit/get/id")
    public BaseResponse<JudgeVO> getJudgeResult(Long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (ObjectUtil.isEmpty(questionSubmit)) {
            return ResultUtils.success(new JudgeVO(), "数据为空");
        }
        Integer status = questionSubmit.getStatus();
        if (QuestionSubmitStatusEnum.WAITING.getValue().equals(status)|| QuestionSubmitStatusEnum.RUNNING.getValue().equals(status)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "判题中");
        }
        JudgeVO judgeVO = CopyUtil.copy(questionSubmit, JudgeVO.class);
        JudgeInfo judgeInfo = JSONUtil.toBean(questionSubmit.getJudgeInfo(), JudgeInfo.class);
        judgeVO.setTime(ObjectUtil.defaultIfNull(judgeInfo.getTime(), 0) + "ms");
        judgeVO.setMemory(ObjectUtil.defaultIfNull(judgeInfo.getMemory(), 0) + "MB");
        judgeVO.setMessage(judgeInfo.getMessage());
        return ResultUtils.success(judgeVO);
    }

    @GetMapping("/getMaxId")
    public int getMaxQuestionId(){
        return questionService.getMaxQuestionId();
    }

    // TODO
//    @PostConstruct
//    private void start(){
//        List<Question> questionList = questionService.list();
//        for (Question question : questionList) {
//            String code = question.getJudgeCode();
//            QuestionCode questionCode = new QuestionCode();
//            questionCode.setQuestionId(question.getId());
//            questionCode.setCode(code);
//            addJudgeCode(questionCode);
//        }
//    }
}
